<template>
  <el-dialog
    ref="commentDialogRef"
    :visible.sync="dialogVisible"
    :close-on-press-escape="false"
    :close-on-click-modal="false"
    :before-close="handleClose"
    :class="{'mobile-page-dialog':showMobilePage}"
    :append-to-body="appendToBody"
    modal-append-to-body
    lock-scroll
    class="subcribe-common-dialog normal-common-dialog-size"
  >
    <div class="comment-content">
      <DialogTitle title="添加评论" style="margin-bottom: 16px" />
      <div v-if="replyContent.content" class="reply-content">
        <div class="reply-content-box ellipsisTwo">
          <div class="reply-text-box ueditor-content" v-html="replyContent.content" />
        </div>
      </div>
      <!-- 富文本 -->
      <RichEditor
        v-if="dialogVisible"
        v-model="commentVal"
        :editor-height="showMobilePage?150:320"
        :editor-width="showMobilePage?330:750"
        :default-mention="replyUser"
        is-show-mention />
      <div class="footer-btn-group">
        <div class="file-box">
          <span style="margin: 5px 12px 0 0; color: #666">附件</span>
          <upAttachment
            ref="uploadImg"
            :import-api="'/admin/contract/file/upload'"
            :hide-confirm="true"
            :is-disabled="false"
            :file-list="attachmentFile"
            :limit="10"
            btn-text="上传附件"
            style="width: 240px;"
            @upLoadError="createLoading = false"
            @upProgress="createLoading = true"
            @complateSetData="complateSetData"
            @removeFileList="removeFileList"
          />
        </div>
        <div class="user-select-box bottom-checkbox">
          <el-checkbox v-model="isTemp">
            <div class="flex-center">临时评论<InfoIcon content="评论后支持随时删除"/></div>
          </el-checkbox>
        </div>
      </div>
      <div class="footer-action-btn">
        <el-button :disabled="onSending || !sendBtnActive" type="primary" size="small" @click="handleSend">发送</el-button>
        <el-button type="primary" plain size="small" style="margin-left: 16px" @click="handleClose">返回</el-button>
      </div>
    </div>
  </el-dialog>
</template>

<script>
import RichEditor from '@/components/Editor/RichEditor';
import SelectCustomUser from '@/views/legal/process/model/selectCustomUser';
import upAttachment from '@/components/Common/upAttachment/index';
import DialogTitle from '@/components/Title';
import { mapState } from 'vuex';
import { showModal } from '@/utils/message';

export default {
  name: 'CommentDialog',
  components: {
    RichEditor,
    SelectCustomUser,
    upAttachment,
    DialogTitle
  },
  props: {
    commentsId: {
      type: [String, Number],
      default: ''
    },
    commentModule: {
      type: String,
      default: ''
    },
    addCommentApi: {
      type: Function,
      default: () => ({})
    },
    appendToBody: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      commentVal: '',
      dialogVisible: false,
      replyContent: '',
      quoteId: '',
      isTemp: false, // 临时评论
      replyUser: null, // 被回复人员
      onSending: false,
      createLoading: false,
      attachmentFile: []
    };
  },
  computed: {
    ...mapState({
      'showMobilePage': state => state.app.showMobilePage
    }),
    sendBtnActive() {
      if (!this.commentVal) return false;
      const commentContent = this.commentVal.replace(/<\/?(?!(img|table|video)).+?>/g, '');
      return commentContent ? commentContent.replace(/&nbsp;|\s/g, '') : false;
    }
  },
  methods: {
    handleDialogClose() {
      this.resetData();
      this.dialogVisible = false;
    },
    resetData() {
      this.commentVal = '';
      this.replyUser = null;
      this.replyContent = '';
      this.attachmentFile = [];
      this.quoteId = '';
      this.isTemp = false;
    },
    formatCommentVal() {
      // 展示时给@元素块增加样式
      return this.commentVal.replace(/data-w-e-type="mention"/g, `"data-w-e-type="mention" style="color: #406EFF"`);
    },
    // 获取所有评论的@人员id
    getNotifyUserIds() {
      let result = this.commentVal.match(/(%3A)(\d*)(?=%7D)/g);
      if (Array.isArray(result) && result.length) {
        result = result.map(i => {
          return i.replace('%3A', '');
        });
        const ids = result.filter(id => !isNaN(Number(id)));
        return [...new Set(ids)].join();
      }
      return '';
    },
    // 发送评论
    async handleSend() {
      try {
        const sendData = Object.create(null);
        sendData.id = this.commentsId;
        sendData.quoteId = this.quoteId;
        sendData.content = this.formatCommentVal();
        sendData.notifyUserIds = this.getNotifyUserIds();
        sendData.attachment = this.attachmentFile;
        sendData.isTemp = this.isTemp;
        sendData.isNewRichText = true; // 新版富文本可在内部使用@功能，无需在末尾追加人员
        this.onSending = true;
        await this.addCommentApi(sendData);
        this.$emit('sendCallback');
        this.handleDialogClose();
        this.onSending = false;
        this.$message.success('发送成功');
      } catch (err) {
        this.onSending = false;
      }
    },
    // 回复
    handleReply(data) {
      const comment = _.cloneDeep(data);
      this.quoteId = comment.id;
      comment.content = comment.content.replace(/<img(.*?)>/g, `<span>[图片]</span>`);
      comment.content = comment.content.replace(/<video(.*?)>(.*?)<\/video>/g, `<span>[视频]</span>`);
      comment.content = comment.content.replace(/<table(.*?)>(.*?)<\/table>/g, `<span>[表格]</span>`);
      comment.content = comment.content.replace(/&nbsp|\s;/g, '').replace(/<\/?(?!(img|table|video)).*?>/g, ' ');
      comment.content = `<span style="color: #333; font-size: 14px; font-weight: 400">[回复] ${comment.userName}：</span>` + comment.content;
      this.replyContent = comment;
      // 设置被回复人消息，回复时默认显示于富文本
      this.replyUser = { id: comment.userId, userName: comment.userName };
    },
    // 关闭评论
    handleClose() {
      this.cancelConfirm();
    },
    cancelConfirm(title = '评论还未发送，确认关闭吗？') {
      if (this.sendBtnActive) {
        showModal(title, '', {}).then(_ => {
          this.handleDialogClose();
        }).catch(_ => null);
      } else {
        this.handleDialogClose();
      }
    },
    complateSetData({ data, fileName }) {
      this.createLoading = false;
      const fileList = {
        name: fileName,
        url: data.url,
        time: new Date().getTime()
      };
      if (typeof data === 'string') {
        fileList.url = data;
      } else {
        fileList.url = data.url;
      }
      this.attachmentFile.push(fileList);
    },
    removeFileList({ index }) {
      this.attachmentFile.splice(index, 1);
    }
  }
};
</script>

<style scoped lang="scss">
::v-deep .clip-btn {
  z-index: 0 !important;
}
.comment-content {
  width: 100%;
  &::v-deep {
    .editorContainer {
      height: auto !important;
    }
    .file-container {
      max-height: 60px;
      overflow-y: auto;
    }
  }
  .reply-content {
    width: 100%;
    padding: 8px 10px;
    border: 1px solid #eee;
    color: #666;
    border-radius: 4px;
    background-color: #fff;
    margin-bottom: 10px;
    &::v-deep {
      p, ul, ol {
        margin: 0;
      }
    }
    .reply-content-box {
      padding: 0 10px;
      max-height: 3.8em;
      position: relative;
      color: #999;
    }
    .reply-text-box {
      font-size: 12px;
      color: #999 !important;
    }
  }
  .footer-btn-group {
    width: 100%;
    display: flex;
    align-items: self-start;
    justify-content: space-between;
    margin-top: 12px;
    .file-box {
      display: flex;
      align-items: self-start;
      white-space: nowrap;
    }
    .user-select-box {
      display: flex;
      align-items: center;
      > span {
        margin-right: 16px;
        color: #333;
        font-size: 14px;
      }
      ::v-deep .select-custom-user-wrap {
        width: 200px;
      }
    }
    .bottom-checkbox {
      height: 28px;
      ::v-deep .el-checkbox__label {
        font-size: 12px;
        padding-left: 4px;
      }
      ::v-deep .el-checkbox {
        color: #333;
      }
    }
  }
  .footer-action-btn {
    width: 100%;
    display: flex;
    justify-content: center;
    margin-top: 24px;
    position: relative;
    button {
      border: none;
    }
  }
}
.mobile-page-dialog {
  &::v-deep {
    .el-dialog {
      width: 100% !important;
      .el-dialog__close {
        right: -5px !important;
        top: -52px !important;
      }
    }
    .textbus-form-body {
      max-height: 123px !important;
      min-width: 100%;
    }
  }
  .footer-btn-group {
    display: block;
    .user-select-box {
      display: flex;
      margin-top: 20px;
      align-items: center;
      > span {
        margin-right: 12px;
      }
      ::v-deep .select-custom-user-wrap {
        width: 240px;
      }
    }
  }
}
</style>
